﻿using System;
using System.Collections.Generic;
using System.Text;

using MVPlan.Engine.Gases;
using MVPlan.Engine.Modeling;
using MVPlan.Engine.Segment;

namespace MVPlan.Engine.Dive
{
    [Serializable()]
    public class LostGasInfo
	{
        #region Properties

        public Profile OriginalProfile
        {
            get;
            set;
        }

        public Profile Profile
        {
            get;
            set;
        }

        public int Index
        {
            get;
            set;
        }

        public Gas Gas
        {
            get
            {
                return this.OriginalProfile.Gases[this.Index];
            }
        }

        #endregion

        #region Constructor

        public LostGasInfo(Profile p, int index)
        {
            this.OriginalProfile = p;
            this.Profile = (Profile)this.OriginalProfile.Clone();
            this.Index = index;

            this.Calculate();
        }

        #endregion

        #region Methods

        public override string ToString()
        {
            double diff = this.Profile.RunTime - this.OriginalProfile.RunTime;

            return string.Format("Lost Gas: {0}; RT: {1}min; Diff: {2}min; {3}", this.Gas, this.Profile.RunTime.ToString("F0"), diff.ToString("F0"), this.Profile.WarningsString);
        }

        protected void Calculate()
        {
            this.Profile.Model = new Model();
            this.Profile.Model.InitialiseModel();
            this.Profile.Model.Gradient.GfLow = Prefs.Current.GfLowBailout;
            this.Profile.Model.Gradient.GfHigh = Prefs.Current.GfHighBailout;

            this.Profile.Gases.RemoveAt(this.Index);            
            
            this.Profile.Gases.Sort(new GasModComparer());

            foreach (SegmentAbstract s in this.Profile.InputSegments)
            {
                if (s.Gas.ShortName == this.Gas.ShortName)
                {
                    s.Gas = null;

                    foreach (Gas g in this.Profile.Gases)
                    {
                        g.MOD = Util.CalcMod(g.FO2, Prefs.Current.PPO2Max);

                        if (g.MOD <= s.Depth)
                        {
                            s.Gas = g;
                        }
                    }

                    if (s.Gas == null)
                    {
                        s.Gas = this.Profile.Gases[0];
                    }
                }
            }

            this.Profile.DoDive();
        }

        #endregion
    }
}
